// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.web.action;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.RegisterService;
import net.taviscaron.drivenotes.web.converter.FormConverter;
import net.taviscaron.drivenotes.web.converter.InvalidFormException;
import net.taviscaron.drivenotes.web.core.Constants;
import net.taviscaron.drivenotes.web.forward.ActionRedirect;
import net.taviscaron.drivenotes.web.forward.RequestForwarder;
import net.taviscaron.drivenotes.web.forward.ViewForward;
import org.springframework.beans.factory.annotation.Required;

/**
 * Register action
 * @author Andrei Senchuk
 */
public class RegisterAction implements Action {
    public enum Error {
        INVALID_FORM
    }

    private RegisterService registerService;
    private FormConverter<User> userConverter;

    @Required
    public void setRegisterService(RegisterService registerService) {
        this.registerService = registerService;
    }

    @Required
    public void setUserConverter(FormConverter<User> userConverter) {
        this.userConverter = userConverter;
    }

    public RequestForwarder doAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(request.getAttribute(Constants.AUTHORIZED_USER_ATTR_NAME) != null) {
            return new ActionRedirect("garage");
        }

        String subaction = request.getParameter(Constants.SUBACTION_PARAM_NAME);
        if(subaction == null) {
            return new ViewForward("register");
        } else if("save".equals(subaction)) {
            try {
                User user = userConverter.convert(request.getParameterMap());
                registerService.registerUser(user);
                return new ActionRedirect("login");
            } catch (InvalidFormException e) {
                request.setAttribute("error", Error.INVALID_FORM);
                return new ViewForward("register");
            } catch (InvalidEntityException e) {
                request.setAttribute("error", e.getReason());
                return new ViewForward("register");
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
    }
}
